package com.levi.test.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializableUtil {

    // 序列化
    public static byte[] writeObj(Object obj) {
        byte[] data = null;
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(obj);
            data = outputStream.toByteArray();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return data;
    }

    // 反序列化
    public static Object readObj(InputStream in) {
        Object obj = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(in);
            obj = objectInputStream.readObject();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return obj;
    }

    // 反序列化
    public static Object readObj(byte[] data) {
        Object obj = null;
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            obj = objectInputStream.readObject();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return obj;
    }
}
